import Util from 'util';

class HttpProvider {
    constructor() {
    }

    __defaultRequest(
        method = '',
        url = '',
        params = {},
        header = {},
        dataType = 'json',
        showLoading = true) {
        let $header = this.getSessionHeader(header);

        let $$config = {
            url: this.getUrl(url),
            data: params,
            header: $header,
            method: method,
            dataType: dataType
        };

        showLoading && wx.showLoading({
            title: '加载中...',
            mask: true,
        })

        return new Promise((resolve, reject) => {
            $$config['success'] = function (res) {
                if (res.statusCode != 200) {
                    reject(res);
                } else {
                    resolve(res.data)
                }
            };

            $$config['fail'] = function (failResponse) {
                reject(failResponse);
            };

            $$config['complete'] = function (completeResponse) {
                showLoading && wx.hideLoading()
                if (completeResponse && completeResponse.statusCode && completeResponse.statusCode != 200) {
                    reject(completeResponse);
                }
            };

            wx.request($$config)
        })
    }

    doPostRequest(url = '',
        params = {},
        header = {},
        dataType = 'json',
        showLoading = true) {
        header = Object.assign({}, header, { "content-type": "application/x-www-form-urlencoded;charset=UTF-8" })
        return this.__defaultRequest('POST', url, params, header, dataType, showLoading);

    }

    doPutRequest(url = '',
        params = {},
        header = {},
        dataType = 'json',
        showLoading = true) {
        header = Object.assign({}, header, { "content-type": "application/x-www-form-urlencoded" })

        return this.__defaultRequest('PUT', url, params, header, dataType, showLoading);

    }

    doGetRequest(url = '',
        params = {},
        header = {},
        dataType = 'json',
        showLoading = true) {
        return this.__defaultRequest('GET', url, params, header, dataType, showLoading);

    }

    getUrl(url) {
        return Util.getRpcUrl(url);
    }

    // 获取session验证的头信息
    getSessionHeader(header) {
        return Object.assign({},
            {
                'userId': getApp().CurrentUser.getUserId(),
            },
            header
        );
    }


}

export default HttpProvider;